package org.van.carfimodulesfinancial.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.van.carfi.common.kernel.constant.LogActions;
import org.van.carfi.common.kernel.constant.UserGenderConst;
import org.van.carfi.common.kernel.constant.WebConst;
import org.van.carfimodulesfinancial.model.UserDomain;
import org.van.carfimodulesfinancial.service.log.LogService;
import org.van.carfimodulesfinancial.service.user.UserService;
import org.van.carfi.common.kernel.utils.APIResponse;
import org.van.carfi.common.kernel.utils.GsonUtils;
import org.van.carfimodulesfinancial.utils.TaleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Api(tags="用户管理")
@Controller
@RequestMapping("/api/user")
public class AuthController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @RequestMapping("hello-financial")
    @ResponseBody
    public String say(){
        return "HelloFinancial";
    }

    @ApiOperation("用户登录")
    @PostMapping(value = "/login",  consumes=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public APIResponse<?> toLogin(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody String body) {
        Map<String, String> map = GsonUtils.getMapFromJson(body, HashMap.class);
        String userAccount = map.get("userAccount");
        String password = map.get("password");
        Integer error_count = cache.get("login_error_count");
        try {
            UserDomain userInfo = userService.login(userAccount, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);
            // 设置cookie标识已登录
            TaleUtils.setCookie(response, userInfo.getUid());
            response.addCookie(new Cookie("failure_time",
                    String.valueOf(System.currentTimeMillis()/1000000+20000)));
            logService.addLog(LogActions.LOGIN.getAction(), userInfo.getUname() + "User", request.getRemoteAddr(),
                    userInfo.getUid());
        } catch (Exception e) {
//            LOGGER.error(e.getMessage());
//            error_count = null == error_count ? 1 : error_count + 1;
//            if (error_count > 3) {
//                return APIResponse.fail("Try it again 10min later!");
//            }
//            System.out.println(error_count);
//            cache.set("login_error_count", error_count, 10 * 60);
//            String msg = "Login Failed!";
//            if (e instanceof BusinessException) {
//                msg = e.getMessage();
//            } else {
//                LOGGER.error(msg, e);
//            }
//            return APIResponse.fail(msg);
            return APIResponse.fail(e.toString());
        }
        return APIResponse.success();
    }

    @RequestMapping(value = "/logout")
    public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setValue(null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    @RequestMapping(value = "/register")
    @ResponseBody
    public APIResponse<?> register(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody String body) {

        Map<String, String> map = GsonUtils.getMapFromJson(body, HashMap.class);
        String userAccount = map.get("userAccount");
        String password = map.get("password");
        String gender = map.get("gender");
        String info = map.get("info");
        String userName = map.get("userName");

        UserDomain user = new UserDomain();
        user.setUacc(userAccount);
        user.setUname(userName);
        user.setUpassword(password);
        user.setUinfo(info);
        try{user.setUgender(UserGenderConst.valueOf(gender));} catch (Exception e) {}

        try {
            userService.register(user);

        } catch (Exception e){
            return APIResponse.fail(e.toString());
        }
        return APIResponse.success();
    }

    @RequestMapping(value = "/info")
    @ResponseBody
    public APIResponse<?> getInfo(
            HttpServletRequest request,
            HttpServletResponse response){

        String uid = "";
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(WebConst.USER_IN_COOKIE)) {
                uid = cookie.getValue();
            }
        }

        try {
            UserDomain user = userService.getUserInfoById(Integer.parseInt(uid));
            return APIResponse.success(user);
        } catch (Exception e){
            return APIResponse.fail(e.toString());
        }
    }
    @RequestMapping(value = "/user-info")
    @ResponseBody
    public APIResponse<?> getUserInfo(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody String body) {


        Map<String, String> map = GsonUtils.getMapFromJson(body, HashMap.class);
        String uid = map.get("uid");

        try {
            UserDomain user = userService.getUserBriefInfoById(Integer.parseInt(uid));
            return APIResponse.success(user);
        } catch (Exception e) {
            return APIResponse.fail(e.toString());
        }
    }

}
